package com.yuju.login.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuju.cache.RedisCache;
import com.yuju.common.core.dao.IBaseDao;
import com.yuju.common.core.service.AbstractBaseService;
import com.yuju.constant.CacheKey;
import com.yuju.enums.ChangePasswordReturnCodeEnum;
import com.yuju.enums.LoginReturnCodeEnum;
import com.yuju.enums.RegisterReturnCodeEnum;
import com.yuju.exception.BusinessException;
import com.yuju.login.dao.entity.Op;
import com.yuju.login.model.OpModel;
import com.yuju.login.service.IChangePasswordService;
import com.yuju.login.service.ILoginService;
import com.yuju.login.service.IOpService;
import com.yuju.util.Utils;
@Service
public class ChangePasswordServiceImpl extends AbstractBaseService<OpModel, Op, String> implements IChangePasswordService{

	@Autowired
	private IOpService opService;
	
	public IBaseDao<OpModel, Op, String> getDao() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public int changePassword(OpModel opModel) {
		//根据手机号验证验证码
		RedisCache simpleCache = RedisCache.getInstance();
		String cacheVerCode = (String) simpleCache.get(opModel.getMobile() + CacheKey.KEY_CACHE_GET_PWD_VERIFY_CODE);
		//如果验证码失效，抛出失效异常信息
		if(Utils.isNull(simpleCache)){
			throw new BusinessException(RegisterReturnCodeEnum.CODE_FAILURE.getCode()
					, RegisterReturnCodeEnum.CODE_FAILURE.getDesc());
		}
		//判断手机号是否已注册
		OpModel m = new OpModel();
		m.setName(opModel.getMobile());
		List<OpModel> list = opService.list(m);
		if(list.size() == 0){
			throw new BusinessException(ChangePasswordReturnCodeEnum.NOT_REGISTERED.getCode()
					, ChangePasswordReturnCodeEnum.NOT_REGISTERED.getDesc());
		}
		
		//判断验证码是否正确，错误则抛出 ，验证码错误异常
		if(!opModel.getVerificationCode().equals(cacheVerCode) ){
			throw new BusinessException(RegisterReturnCodeEnum.CODE_VAILD_FAILURE.getCode()
					, RegisterReturnCodeEnum.CODE_VAILD_FAILURE.getDesc());
		}
		//判断两次密码输入是否一致
		if(!opModel.getPassword().equals(opModel.getConfirmPassword())){
			throw new BusinessException(ChangePasswordReturnCodeEnum.PASSWORD_MISMATCH.getCode()
					, ChangePasswordReturnCodeEnum.PASSWORD_MISMATCH.getDesc());
		}
		//更改账号密码
		int i = opService.updateWxGuest(opModel);
		return i;
	}
}